import { defineStore } from "pinia";
// 更可靠的方式是将文件放在 public 目录下
const song1Url =
  "https://mp-dcc57d1b-9703-4fa7-bf3e-a2bebe5587bd.cdn.bspapp.com/mysite_music/song1.mp3";
const song2Url =
  "https://mp-dcc57d1b-9703-4fa7-bf3e-a2bebe5587bd.cdn.bspapp.com/mysite_music/song2.mp3";
const song3Url =
  "https://mp-dcc57d1b-9703-4fa7-bf3e-a2bebe5587bd.cdn.bspapp.com/mysite_music/song3.mp3";

export const useAudioPlayerStore = defineStore("audioPlayer", () => {
  const audioRef = ref<HTMLAudioElement | null>(null);
  const isPlaying = ref(false);
  const currentTime = ref(0);
  const duration = ref(0);
  const currentSongIndex = ref(0);
  const songs = ref([song1Url, song2Url, song3Url]);
  const isInitialized = ref(false);

  const progressPercentage = computed(() => {
    return duration.value > 0 ? (currentTime.value / duration.value) * 100 : 0;
  });

  const currentSongUrl = computed(() => songs.value[currentSongIndex.value]);

  const updateProgress = () => {
    if (audioRef.value) {
      currentTime.value = audioRef.value.currentTime;
      // 只有在 duration 是有效数字时才更新
      if (
        !isNaN(audioRef.value.duration) &&
        isFinite(audioRef.value.duration)
      ) {
        duration.value = audioRef.value.duration;
      } else {
        duration.value = 0; // 重置为0或保持上一个有效值
      }
    }
  };

  const handleEnded = () => {
    playNext();
  };

  const handleError = (e: Event) => {
    console.error("Audio Error:", e);
    isPlaying.value = false; // 出错时重置状态
    // 可以在这里添加更复杂的错误处理逻辑，例如尝试重新加载或跳到下一首
  };

  const setupAudioListeners = () => {
    if (!audioRef.value) return;
    audioRef.value.addEventListener("timeupdate", updateProgress);
    audioRef.value.addEventListener("loadedmetadata", updateProgress);
    audioRef.value.addEventListener("ended", handleEnded);
    audioRef.value.addEventListener("play", () => (isPlaying.value = true));
    audioRef.value.addEventListener("pause", () => (isPlaying.value = false));
    audioRef.value.addEventListener("error", handleError);
  };

  const removeAudioListeners = () => {
    if (!audioRef.value) return;
    audioRef.value.removeEventListener("timeupdate", updateProgress);
    audioRef.value.removeEventListener("loadedmetadata", updateProgress);
    audioRef.value.removeEventListener("ended", handleEnded);
    audioRef.value.removeEventListener("play", () => (isPlaying.value = true));
    audioRef.value.removeEventListener(
      "pause",
      () => (isPlaying.value = false)
    );
    audioRef.value.removeEventListener("error", handleError);
  };

  const initializeAudio = () => {
    if (typeof window === "undefined" || isInitialized.value) return; // 防止在 SSR 或重复初始化
    console.log("Initializing audio...");
    audioRef.value = new Audio();
    audioRef.value.src = currentSongUrl.value;
    setupAudioListeners();
    isInitialized.value = true;
    console.log("Audio initialized.");
  };

  const cleanupAudio = () => {
    console.log("Cleaning up audio...");
    if (audioRef.value) {
      removeAudioListeners();
      audioRef.value.pause();
      audioRef.value.src = ""; // 释放资源
      audioRef.value = null;
    }
    isInitialized.value = false;
    isPlaying.value = false;
    currentTime.value = 0;
    duration.value = 0;
    console.log("Audio cleaned up.");
  };

  const loadSong = (index: number) => {
    if (!audioRef.value || !isInitialized.value) {
      console.warn("Audio not initialized, cannot load song.");
      // 尝试初始化（如果尚未完成）
      if (!isInitialized.value) initializeAudio();
      // 如果初始化后仍然失败，则退出
      if (!audioRef.value) return;
    }

    currentSongIndex.value = index;
    const newSrc = songs.value[index];
    console.log(`Loading song: ${newSrc}`);

    // 只有当 src 改变时才设置，避免不必要的重载
    if (audioRef.value.currentSrc !== newSrc) {
      audioRef.value.src = newSrc;
      audioRef.value.load(); // 重新加载音频
    }

    // 重置时间和播放状态（根据需要）
    currentTime.value = 0;
    // duration.value = 0; // loadedmetadata 会更新它

    // 如果之前是播放状态，加载新歌后尝试自动播放
    if (isPlaying.value) {
      // 延迟播放以确保加载完成
      setTimeout(() => {
        audioRef.value?.play().catch((e) => {
          console.error("Audio play failed after load:", e);
          isPlaying.value = false; // 播放失败则重置状态
        });
      }, 100);
    } else {
      // 如果之前是暂停状态，加载后保持暂停
      isPlaying.value = false;
    }
  };

  const togglePlay = () => {
    if (!audioRef.value || !isInitialized.value) {
      console.warn("Audio not initialized, cannot toggle play.");
      if (!isInitialized.value) initializeAudio();
      if (!audioRef.value) return;
    }
    if (isPlaying.value) {
      console.log("Pausing audio");
      audioRef.value.pause();
    } else {
      console.log("Playing audio");
      // 尝试播放，处理可能的 Promise rejection
      audioRef.value.play().catch((e) => {
        console.error("Audio play failed:", e);
        playNext(); // 播放失败后尝试下一首
      });
    }
    // 注意：播放状态由 'play' 和 'pause' 事件监听器更新，这里不需要手动设置 isPlaying.value
  };

  const playNext = () => {
    const nextIndex = (currentSongIndex.value + 1) % songs.value.length;
    console.log(`output->nextIndex`, nextIndex);
    loadSong(nextIndex);
    setTimeout(() => {
      if (audioRef.value) {
        audioRef.value.play().catch((e) => {
          console.error("Audio play failed after playNext:", e);
          isPlaying.value = false; // Reset state on failure
        });
      }
    }, 150);
  };

  const playPrevious = () => {
    const prevIndex =
      (currentSongIndex.value - 1 + songs.value.length) % songs.value.length;
    loadSong(prevIndex);
  };

  const formatTime = (time: number): string => {
    // 确保时间是非负数
    if (isNaN(time) || !isFinite(time) || time < 0) return "0:00";
    // 处理浮点数精度问题
    const roundedTime = Math.round(time);
    const minutes = Math.floor(roundedTime / 60);
    const seconds = Math.floor(roundedTime % 60);
    return `${minutes}:${seconds < 10 ? "0" : ""}${seconds}`;
  };

  // 提供一个方法来确保在客户端初始化
  const ensureInitialized = () => {
    if (!isInitialized.value) {
      initializeAudio();
    }
  };

  return {
    audioRef, // 谨慎暴露 audioRef
    isPlaying,
    currentTime,
    duration,
    currentSongIndex,
    songs,
    progressPercentage,
    currentSongUrl,
    isInitialized,

    initializeAudio, // 或者使用 ensureInitialized
    cleanupAudio,
    loadSong,
    togglePlay,
    playNext,
    playPrevious,
    formatTime,
    ensureInitialized,
  };
});
